<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-title">欢迎登录</div>
      <el-form ref="loginForm" :model="loginFormData" label-width="0px" size="medium">
        <el-form-item prop="username">
          <el-input v-model="loginFormData.account" placeholder="用户名" prefix-icon="el-icon-user"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginFormData.password" type="password" placeholder="密码" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input v-model="loginFormData.code" placeholder="验证码" prefix-icon="el-icon-key"></el-input>
          <img class="captcha-image" :src="captchaImageUrl" @click="refreshCaptcha" alt="验证码" />
        </el-form-item>
        <div class="login-button-container">
          <el-button type="primary" style="width: 100%" @click="login">登录</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {loginAPI} from "@/api/sys/login"
import {getDeviceId} from "@/utils/device"
import { useRouter } from 'vue-router'
import {getUserToken,saveUserToken,isAuthentication} from "@/utils/usertoken"
import {ElMessage} from 'element-plus'


//拿到路由器
const router = useRouter();
const loginForm = ref();
const  loginFormData = ref({
  account: '',
  password: '',
  code: '',
  deviceId: getDeviceId()
})

const  login = ()=>{
  console.log("登录的数据：",loginFormData.value)
  //需要要外面先拿到router

  loginAPI(loginFormData.value)
      .then(res=>{
        if (res.data.code === 200) {
          //后端返回令牌
          let logResp = res.data.data;
          //保存用户令牌
          saveUserToken(logResp);
          //跳转到Dashboard； promise里面的this和外面的this，不是一个this
          router.push("/")
        }else {
          ElMessage.error(res.data.message)
          refreshCaptcha();
          loginFormData.value= {
            account: '',
            password: '',
            code: '',
            deviceId: getDeviceId()
          }
        }
      })

}


//验证码
const captchaImageUrl = ref(`http://localhost/api/sys/captcha?deviceId=${getDeviceId()}`)
const refreshCaptcha = ()=>{
  //请求后面加上时间，防止浏览器请求结果缓存。
  captchaImageUrl.value = `http://localhost/api/sys/captcha?deviceId=${getDeviceId()}&` + new Date().getTime(); // 示例中假设后端路由为'/api/generate-captcha'
}
</script>

<style scoped>
/* 新增样式用于居中按钮 */
.login-button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px; /* 调整按钮与输入框之间的距离 */
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.login-card {
  width: 400px;
  text-align: center;
  padding: 20px;
}

.login-title {
  font-size: 24px;
  margin-bottom: 20px;
}
</style>
